package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.ReentrantReadWriteLock;

@Service
@Slf4j
public class ReentrantReadWriteLockCacheService {

    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private String cacheData = null;

    // 模拟从数据库加载数据
    private String loadDataFromDB() {
        try {
            Thread.sleep(1000); // 模拟数据库读取时间
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return "数据库中的数据";
    }

    // 读取缓存数据
    public String readData() {
        rwLock.readLock().lock();
        try {
            if (cacheData == null) {
                log.info("缓存未命中，准备加载数据...");
                rwLock.readLock().unlock(); // 释放读锁
                rwLock.writeLock().lock();  // 获取写锁
                try {
                    if (cacheData == null) { // 双重检查
                        log.info("从数据库加载数据...");
                        cacheData = loadDataFromDB();
                        log.info("数据加载完成，更新缓存: {}", cacheData);
                    }
                    rwLock.readLock().lock(); // 获取读锁
                } finally {
                    rwLock.writeLock().unlock(); // 释放写锁
                }
            }
            log.info("读取缓存数据: {}", cacheData);
            return cacheData;
        } finally {
            rwLock.readLock().unlock();
        }
    }

    // 清空缓存数据（模拟缓存失效）
    public void invalidateCache() {
        rwLock.writeLock().lock();
        try {
            log.info("清空缓存");
            cacheData = null;
        } finally {
            rwLock.writeLock().unlock();
        }
    }
}
